<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/9/19 10:00
 * Desc:
 */
class Service_Api_Integral_Award extends Contract_Api_Integral_Award
{

    public function award(): array
    {
        //抽奖活动信息
        $info = DB::select('id', 'title', 'start_time', 'content', 'need_jifen')
            ->from('integral_award')
            ->where('is_hidden', '=', 0)
            ->and_where('status', '=', 1)
            ->order_by('id', 'desc')
            ->execute()
            ->current();

        //奖品套餐
        $suit = DB::select('product_name', 'litpic', 'index', 'award_type_id')
            ->from('integral_award_suit')
            ->where('award_id', '=', $info['id'])
            ->order_by('index', 'asc')
            ->execute()
            ->as_array();
        foreach ($suit as & $v) {
            $v['litpic'] = $this->img_url($v['litpic']);
        }

        //中奖纪录
        $winner = DB::select('member_nickname', 'product_name', 'addtime')
            ->from('integral_winner')
            ->where('award_id', '=', $info['id'])
            ->and_where('product_name', 'not like', '%谢谢%')
            ->limit(12)
            ->execute()
            ->as_array();

        return array(
            'info' => $info,
            'suit' => $suit,
            'winner' => $winner,
        );
    }

    public function get_award_log(int $mid, array $params): array
    {
        /**
         * @var $page
         * @var $pagesize
         */
        extract($params);

        $builder = DB::select(
            'integral_winner.member_nickname',
            'integral_winner.product_name',
            'integral_winner.addtime',
            'integral_winner.award_id',
            'integral_winner.suit_id',
            'integral_award.title'
        )
            ->from('integral_winner')
            ->join('integral_award', 'left')
            ->on('integral_winner.award_id', '=', DB::expr('sline_integral_award.id'))
            ->where('member_id', '=', $mid);

        if (!empty($page) && !empty($pagesize)) {
            $offset = St_Page::offset($page, $pagesize);
            $builder->offset($offset)->limit($pagesize);
        }

        $list = $builder->and_where('product_name', 'not like', '%谢谢%')
            ->order_by('addtime', 'desc')
            ->execute()
            ->as_array();
        foreach ($list as & $v) {
            $v['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
            $litpic = DB::select()->from('integral_winner')->where('id','=',$v['suit_id'])->execute()->get('litpic');
            $v['litpic'] = $this->img_url($litpic,160,160);
        }

        return $list;
    }

    public function luck_draw(int $mid, int $id): array
    {
        $award = DB::select()
            ->from('integral_award')
            ->where('id', '=', $id)
            ->and_where('is_hidden', '=', 0)
            ->execute()
            ->current();

        if (!$award || $award['status'] != 1) {
            throw new Exception('抽奖已结束');
        }

        //用户信息
        $member = Model_Member::get_member_byid($mid);
        if ($member['jifen'] < $award['need_jifen'] && $member['jifen_lottery_num']<0) {
            throw new Exception('很遗憾，您的可用积分不足，无法参与抽奖');
        }

        $jifen = $award['need_jifen'];
        $type = 0;
        if($member['jifen_lottery_num']>0){
            $type = 1;
            DB::update('member')
                ->set(array('jifen_lottery_num' => DB::expr("jifen_lottery_num-1")))
                ->where('mid', '=', $mid)
                ->execute();
        }else{
            //扣除用户积分
            DB::update('member')
                ->set(array('jifen' => DB::expr("jifen-{$jifen}")))
                ->where('mid', '=', $mid)
                ->execute();

            St_Product::add_jifen_log($mid, "参与第{$id}期积分抽奖，使用{$jifen}积分", $jifen, 1);
        }

        //抽奖处理
        $award_model = new Model_Api_V2_Integral_Award();
        $award       = $award_model->is_luck($id);

        //减少数量
        DB::update('integral_award_suit')
            ->set(array('number' => DB::expr('number-1')))
            ->where('id', '=', $award['id'])
            ->execute();

        //写入中奖记录
        $log = array(
            'member_id' => $mid,
            'member_nickname' => $member['nickname'],
            'product_name' => $award['product_name'],
            'award_id' => $award['award_id'],
            'suit_id' => $award['id'],
            'addtime' => time()
        );
        if($type==1){
            $log['use_num'] = 1;
        }else{
            $log['use_jifen'] = $jifen;
        }

        if ($award['award_type_id'] == 1) {
            $log['link_name'] = $member['nickname'];
            $log['link_tel']  = $member['mobile'];
        }

        if ($award['award_type_id'] == 2) {
            $log['link_name'] = '无';
        }

        list($winner_log_id) = DB::insert('integral_winner', array_keys($log))
            ->values(array_values($log))
            ->execute();

        //中奖类型为积分
        if ($award['award_type_id'] == 1 && preg_match('~ig_(\d+)~', $award['value'], $match)) {
            $obj   = DB::select()
                ->from('jifen')
                ->where('id', '=', $match[1])
                ->execute()
                ->current();
            $jifen = Model_Jifen::reward_jifen($obj['label'], $mid);
            if ($jifen) {
                $content = "参与第{$id}期积分抽奖，中奖{$jifen}积分";
                St_Product::add_jifen_log($mid, $content, $jifen, 2);
            }
        }

        return array('luck_number' => $award['index'], 'log_id' => $winner_log_id, 'title' => $award['product_name'], 'type' => $award['award_type_id']);
    }

    public function save_award_info(int $mid, array $params): array
    {
        /**
         * @var $id
         * @var $link_name
         * @var $link_tel
         */
        extract($params);

        $winner = DB::select()
            ->from('integral_winner')
            ->where('id', '=', $id)
            ->where('member_id', '=', $mid)
            ->execute()
            ->current();
        if (!$winner) {
            throw new Exception('中奖记录不存在');
        }

        $data = array(
            'link_name' => $link_name,
            'link_tel' => $link_tel
        );
        DB::update('integral_winner')
            ->set($data)
            ->where('id', '=', $id)
            ->execute();

        return array();
    }
}